#include "AppDelegate.h"
#include "GeneratedPluginRegistrant.h"
//    ------- jpush - begin
// 引入JPush功能所需头文件
#import "JPUSHService.h"
// iOS10注册APNs所需头文件
#ifdef NSFoundationVersionNumber_iOS_9_x_Max
#import <UserNotifications/UserNotifications.h>
#endif
// 如果需要使用idfa功能所需要引入的头文件（可选）
#import <AdSupport/AdSupport.h>
//    ------- jpush -   end
//    ------- flutter - begin
#import <Flutter/Flutter.h>
//    ------- flutter -   end
#define API_KEY @"D77oMv1vh"
#define USER_ID @"U000002139"
#define WALLET @"W000002360"

@interface AppDelegate ()<JPUSHRegisterDelegate>

@end

@implementation AppDelegate

- (BOOL)application:(UIApplication *)application
    didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
  [GeneratedPluginRegistrant registerWithRegistry:self];
  // Override point for customization after application launch.
//    ------- latipay - begin
    [LatipaySDK setupWithApiKey:API_KEY userId:USER_ID walletId:WALLET];
//    ------- latipay -   end
//    ------- jpush - begin
    //Required
    //notice: 3.0.0及以后版本注册可以这样写，也可以继续用之前的注册方式
    JPUSHRegisterEntity * entity = [[JPUSHRegisterEntity alloc] init];
    entity.types = JPAuthorizationOptionAlert|JPAuthorizationOptionBadge|JPAuthorizationOptionSound;
    if ([[UIDevice currentDevice].systemVersion floatValue] >= 8.0) {
        // 可以添加自定义categories
        // NSSet<UNNotificationCategory *> *categories for iOS10 or later
        // NSSet<UIUserNotificationCategory *> *categories for iOS8 and iOS9
    }
    [JPUSHService registerForRemoteNotificationConfig:entity delegate:self];
    
    // Optional
    // 获取IDFA
    // 如需使用IDFA功能请添加此代码并在初始化方法的advertisingIdentifier参数中填写对应值
    NSString *advertisingId = [[[ASIdentifierManager sharedManager] advertisingIdentifier] UUIDString];
    
    // Required
    // init Push
    // notice: 2.1.5版本的SDK新增的注册方法，改成可上报IDFA，如果没有使用IDFA直接传nil
    // 如需继续使用pushConfig.plist文件声明appKey等配置内容，请依旧使用[JPUSHService setupWithOption:launchOptions]方式初始化。
    [JPUSHService setupWithOption:launchOptions appKey:@"b7537b4098cb27964a1289f8"
                          channel:@"App Store"
                 apsForProduction:NO
            advertisingIdentifier:advertisingId];
//    ------- jpush -   end
    
    //    ------- flutter - begin
    FlutterViewController* controller = (FlutterViewController*)self.window.rootViewController;
    
    FlutterMethodChannel* deviceIdChannel = [FlutterMethodChannel
                                            methodChannelWithName:@"cn.dujc.citiesocial"
                                            binaryMessenger:controller];
    
    [deviceIdChannel setMethodCallHandler:^(FlutterMethodCall* call, FlutterResult result) {
        _flutterResult = nil;
        if ([@"getDeviceId" isEqualToString:call.method]) {
            //            NSString *string =[[ NSString alloc] initWithData:_myDeviceToken encoding:NSUTF8StringEncoding];
            if (_myDeviceId == nil || _myDeviceId == NULL || _myDeviceId.length == 0) {
                _myDeviceId = [JPUSHService registrationID];
            }
            result(_myDeviceId);
        }else if ([@"alipay" isEqualToString:call.method]
                  || [@"wechat" isEqualToString:call.method]) {
            _flutterResult = result;
            //    ------- latipay - begin
            NSString * amount = call.arguments[@"amount"];
            NSString * merchantReference = call.arguments[@"merchantReference"];
            NSString * productName = call.arguments[@"productName"];
            NSString * callbackUrl = call.arguments[@"callbackUrl"];
            NSDictionary * params = [NSDictionary dictionaryWithObjectsAndKeys:
                                     amount,@"amount",
                                     merchantReference,@"merchant_reference",
                                     productName,@"product_name",
                                     callbackUrl,@"callback_url",
                                     call.method,@"payment_method"
                                     , nil];
            [LatipaySDK pay:params completion:^(NSDictionary<NSString *,NSString *> * _Nullable result, NSError * _Nullable error) {
                NSLog(@"pay : result = %@", result);
                NSLog(@"pay : error = %@", error);
            }];
//            result(_myDeviceId);
            //    ------- latipay -   end
        }else{
            result(@"");
        }
    }];
    //    ------- flutter -   end

  return [super application:application didFinishLaunchingWithOptions:launchOptions];
}

//    ------- jpush - begin
- (void)application:(UIApplication *)application
didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
//    _myDeviceToken=deviceToken;
    /// Required - 注册 DeviceToken
    [JPUSHService registerDeviceToken:deviceToken];
}
#pragma mark- JPUSHRegisterDelegate

// iOS 10 Support
- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(NSInteger))completionHandler {
    // Required
    NSDictionary * userInfo = notification.request.content.userInfo;
    if([notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
        [JPUSHService handleRemoteNotification:userInfo];
    }
    completionHandler(UNNotificationPresentationOptionAlert); // 需要执行这个方法，选择是否提醒用户，有Badge、Sound、Alert三种类型可以选择设置
}

// iOS 10 Support
- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)())completionHandler {
    // Required
    NSDictionary * userInfo = response.notification.request.content.userInfo;
    if([response.notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
        [JPUSHService handleRemoteNotification:userInfo];
    }
    completionHandler();  // 系统要求执行这个方法
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
    
    // Required, iOS 7 Support
    [JPUSHService handleRemoteNotification:userInfo];
    completionHandler(UIBackgroundFetchResultNewData);
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
    
    // Required,For systems with less than or equal to iOS6
    [JPUSHService handleRemoteNotification:userInfo];
}
//    ------- jpush -   end

//    ------- latipay - begin
- (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary<UIApplicationOpenURLOptionsKey,id> *)options{
    [LatipaySDK processPaymentResultWithUrl:url completion:^(NSDictionary<NSString *,NSString *> * _Nonnull result) {
        NSString * status = result[@"status"];
        if (status != nil && _flutterResult != nil) {
            if ([[NSString stringWithFormat:@"%ld",kPaymentStatusPaid] isEqualToString:status]) {
                _flutterResult(@"paid");
            } else if ([[NSString stringWithFormat:@"%ld",kPaymentStatusUnpaid] isEqualToString:status]) {
                _flutterResult(@"unpaid");
            } else if ([[NSString stringWithFormat:@"%ld",kPaymentStatusNeedQueryServer] isEqualToString:status]) {
                _flutterResult(@"server");
            } else {
                _flutterResult(@"pending");
            }
        }
        NSLog(@"open url : result = %@", result);
    }];
    return true;
}
//    ------- latipay -   end

@end
